package com.webvihar.common.db;

import java.io.File;
import java.io.FileNotFoundException;

import android.content.Context;

import com.webvihar.common.tests.TestAdapter;
import com.webvihar.common.tests.TestAdapter.TestModes;
import com.webvihar.common.utils.Logger;

public class DbAdapter {
	public static Context currentContext;
	public static final String dbFileName = "access2db.db";
	private static String dbDirectoryPath = "db/v1";

	public static String createDbFile() {
		String fqFilename = null;
		try {
			File localDirectoryPath = getLocalDirectoryPath();
			createDbDirectory(getFullQualifiedDirectoryName(localDirectoryPath));
			fqFilename = getFullyQualifiedDbFilename(localDirectoryPath);
			if (new File(fqFilename).exists()) return fqFilename;
			createTheDbFile(fqFilename);
		}
		catch (Exception e) {
			Logger.logError(Logger.LOG_TAG, e.getMessage());
		}
		return fqFilename;
	}

	private static String getFullyQualifiedDbFilename(File localDirectoryPath) {
		return String.format("%s/%s/%s", localDirectoryPath, dbDirectoryPath, dbFileName);
	}

	private static String getFullQualifiedDirectoryName(File localDirectoryPath) {
		return String.format("%s/%s", localDirectoryPath, dbDirectoryPath);
	}

	/**
	 * This method should only be used by test classes.
	 */
	public static void deleteDbFile() {
		try {
			File file = new File(getFullyQualifiedDbFilename(getLocalDirectoryPath()));
			boolean result = file.delete();
			Logger.logInfo(Logger.LOG_TAG, String.format("Was file *%s* deleted: %s", file == null ? "null" : file.toString(), String.valueOf(result)));
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void createDbDirectory(String fqDirectoryName) {
		File dbDirectory = new File(fqDirectoryName);
		boolean result = false;
		if (!dbDirectory.exists()) result = dbDirectory.mkdirs();
		Logger.logInfo(Logger.LOG_TAG, String.format("Directory named *%s* created: %s", fqDirectoryName, String.valueOf(result)));
		return;
	}

	private static void createTheDbFile(String fqFilename) throws FileNotFoundException {
		if (TestAdapter.testMode == TestModes.TEST) {
			new File(fqFilename);
		}
		else {
			currentContext.openFileOutput(fqFilename, Context.MODE_PRIVATE);
		}
	}

	private static File getLocalDirectoryPath() throws Exception {
		if (TestAdapter.testMode != TestModes.TEST && currentContext == null) throw new Exception(String.format("%s: CurrentContext field was not set and is currently null.  Make sure to set this from your Activity.  ", DbAdapter.class.getName()));
		return TestAdapter.testMode == TestModes.TEST ? new File(".") : currentContext.getFilesDir();
	}
}
